import { exec } from 'child_process'
import resBody from '~/server/utils/resBody'
import extractCurlData from '@/utils/parseCurl'

export default defineEventHandler(async (event) => {
  const body = await readBody(event)
  const curl = body.curl

  try {
    const curlRes = await curlRequest(curl)
    // log(curlRes)
    return resBody.success({
      res: JSON.parse(curlRes),
      req:
        typeof extractCurlData(curl).body === 'object' &&
        extractCurlData(curl).body !== null
          ? {
              ...(extractCurlData(curl).body as object),
              ...extractCurlData(curl).queryParams
            }
          : extractCurlData(curl).queryParams
    })
  } catch (error) {
    // log(error)
    return resBody.error(400, error)
  }
})

function curlRequest(curl: string): Promise<string> {
  return new Promise((resolve, reject) => {
    exec(curl, (error, stdout, stderr) => {
      if (error) {
        reject(error)
      } else {
        resolve(stdout)
      }
    })
  })
}
